<template>
  <el-form-item prop="dataField" :rules="formItemRules">
    <template #label>
      <span>{{i18n.$st('designer.setting.dataField')}}</span>
    </template>
    <el-input type="text" readonly
      placeholder="请选择数据字段"
      v-model="optionModel.dataField"
      :title="optionModel.dataField">
      <template #append>
        <el-button type="primary"
          class="input-select-btn"
          @click="selectDataField()">选择</el-button>
      </template>
    </el-input>
    <DataFieldDialog
      ref="dataFieldDialogRef"
      :optionModel="optionModel"
      @confirm="confirmDataField"
    >
    </DataFieldDialog>
  </el-form-item>
</template>

<script setup name="dataField-editor">

import { DataFieldDialog } from '@/components/dialogs'

import { i18n } from "@/utils/i18n"
import { ref, onMounted } from 'vue'
import { VfMessage } from '@/utils/vf-utils'

import { isEmptyStr } from "@/utils/util"

const props = defineProps({
  // 设计器信息
  designer: { type: Object },
  // 组件选项信息
  optionModel: { type: Object },
  // 当前选中的组件
  selectedWidget: { type: Object }
})

// ----- 初始化
onMounted(() => {
})

// ----- 表单信息
const formItemRules = ref([
  { required: true, message: '请选择数据字段', trigger: ['blur', 'change'] }
])

// ----- 弹出层信息
const dataFieldDialogRef = ref()
/** 选择数据字段 */
const selectDataField = function () {
  dataFieldDialogRef.value.handleOpen()
}
/**
 * 选中数据字段回调
 *
 * @param {Object} row 选中的行数据
 */
const confirmDataField = function (row) {
  const { tableName, columnName, columnComments } = row
  props.selectedWidget.options.code = columnName
  props.selectedWidget.options.dataField = `${tableName}.${columnName}`
  updataWidgetOptions(columnName, columnComments)
}

// ----- 更新其他字段信息
const updataWidgetOptions = function (newName, newLabel) {
  let oldName = props.designer.selectedWidgetName
  if (isEmptyStr(newName) && isEmptyStr(newName)) {
    VfMessage.info(i18n.$st('designer.hint.nameRequired'))
    return
  }
  if (!!props.designer.formWidget) {
    const { getWidgetRef, getWidgetRefs } = props.designer.formWidget
    // 检查newName组件是否存在
    const { count, foundRef, foundRefsKey } = getWidgetRefs(newName)
    // 新的名称与旧的名称相同，返回
    if (foundRefsKey.includes(oldName)) {
      VfMessage.info(i18n.$st('designer.hint.duplicateName') + oldName)
      return
    }
    if (!!foundRef) { newName = `${newName}_${count}` }
    // 获取原有的组件
    const widgetInDesign = getWidgetRef(oldName)
    if (!!widgetInDesign && !!widgetInDesign.registerToRefList) {
      // 修改唯一标识名称
      props.selectedWidget.options.name = newName
      // 注册组件新的ref名称并删除老的ref！！
      widgetInDesign.registerToRefList(oldName)
      // 更新name和label
      props.designer.updateSelectedWidgetNameAndLabel(props.selectedWidget, newName, newLabel)
    }
  }
}

</script>

<style lang="scss" scoped>
.input-select-btn {
  color: #fff !important;
  background-color: #409eff !important;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}
</style>